import 'dart:io';

import 'package:flutter/material.dart';

import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:open_file/open_file.dart';

class AppVersionPage extends StatefulWidget {
  AppVersionPage({Key key}) : super(key: key);

  @override
  _AppVersionPageState createState() => _AppVersionPageState();
}

class _AppVersionPageState extends State<AppVersionPage> {

  bool _isInit = true;

  @override
  void initState(){
    super.initState();

    this._getPackageInfo();
    this._getAppPath();
  }

  //获取版本号
  _getPackageInfo() async{
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String appName = packageInfo.appName;
    String packageName = packageInfo.packageName;
    String version = packageInfo.version;
    String builderNumber = packageInfo.buildNumber;
    
    print('appName: $appName');
    print('packageName: $packageName');
    print('version: $version');
    print('builderNumber: $builderNumber');
  }

  //获取路径
  _getAppPath() async{
    Directory tempDir = await getTemporaryDirectory();
    String tempPath = tempDir.path;

    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path;

    var directory = await getExternalStorageDirectory();
    String storageDirectory = directory.path;

    print('tempPath :$tempPath');
    print('appDocPath: $appDocPath');
    print('storageDirectory: $storageDirectory');
  }

  //下载打开文件
  _download() async{
    if (this._isInit) { //插件必须在使用前初始化
      WidgetsFlutterBinding.ensureInitialized();
      await FlutterDownloader.initialize(
        debug: true
      );
      setState(() {
        this._isInit = false;
      });
    }

    final directory = await getExternalStorageDirectory();
    String _localpath = directory.path;

    final taskId = await FlutterDownloader.enqueue(
      url: 'http://www.ionic.wang/jdshop.apk', 
      savedDir: _localpath,
      showNotification: true,
      openFileFromNotification: true
    );

    FlutterDownloader.registerCallback(downloadCallback);

    //打开文件
    OpenFile.open('$_localpath/jdshop.apk');

  }

  //下载的回调
  static void downloadCallback(id, status, progress) {
    print('任务：$id， 状态： $status， 进度： $progress');
  }

  //弹出Dialog
  _showDialog() async{
    var alertRel = await showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text('更新App提示'),
          content: Text('发现新的版本，新版本修复如下bug...是否更新？'),
          actions: <Widget>[
            FlatButton(
              onPressed: () => Navigator.pop(context, 'Cancle'), 
              child: Text('否')
            ),
            FlatButton(
              onPressed: () => Navigator.pop(context, 'Ok'), 
              child: Text('是')
            )
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.arrow_downward),
        onPressed: _download
      ),
      appBar: AppBar(
        title: Text('检测应用版本') 
      ),
      body: Text('app升级演示'),
    );
  }
}